package com.chinaunicom.emergency.action;

import com.chinaunicom.emergency.annotation.Permission;
import com.chinaunicom.emergency.model.Dictionary;
import com.chinaunicom.emergency.service.DictionaryService;
import com.chinaunicom.emergency.util.Assert;
import com.chinaunicom.emergency.util.UpdateUtil;
import com.chinaunicom.emergency.exception.CheckException;
import com.chinaunicom.emergency.repository.DictionaryRepository;
import com.chinaunicom.emergency.repository.UsersRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * @Author liliang
 * @Date 2019/12/18 15:22
 * @Version 1.0
 */
@RestController
@Api(tags = {"字典管理"})
@RequestMapping("/api/dictionary")
@Log4j2
@RefreshScope
public class DictionaryAction extends BaseAction {

    @Autowired
    DictionaryRepository dictionaryRepository;
    @Autowired
    DictionaryService dictionaryService;
    @Autowired
    UsersRepository usersRepository;


    @ApiOperation("字典新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("dictionary:add")
    @PostMapping(value = "/add")
    public Object add(@RequestBody com.chinaunicom.emergency.model.Dictionary dictionary) throws CheckException {
        Assert.isBlank(dictionary.getDicValue(), "字典值不能为空");
        Assert.isBlank(dictionary.getDicCode(), "字典编码不能为空");
        com.chinaunicom.emergency.model.Dictionary existDictionary = dictionaryRepository.findByParentIdAndDicCodeAndIsSoftDel(dictionary.getParentId(),dictionary.getDicCode(),0);
        Assert.isNotNull(existDictionary,"字典编码重复,请勿重复创建");
        com.chinaunicom.emergency.model.Dictionary existDictionary1 = dictionaryRepository.findByParentIdAndDicValueAndIsSoftDel(dictionary.getParentId(),dictionary.getDicValue(),0);
        Assert.isNotNull(existDictionary1,"同一节点下字典值重复,请勿重复创建");

        dictionary.setIsSoftDel(0);
        dictionary.setCreateBy(getCurrUserId());
        dictionary.setCreateTime(new Date());
        dictionaryRepository.save(dictionary);
        return success();
    }

    @ApiOperation("字典修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("dictionary:update")
    @PutMapping(value = "/update")
    public Object update(@RequestBody com.chinaunicom.emergency.model.Dictionary dictionary) throws CheckException {
        Assert.isBlank(dictionary.getDicValue(), "字典值不能为空");
        Assert.isBlank(dictionary.getDicCode(), "字典编码不能为空");
        Assert.isBlank(dictionary.getPid(), "字典id不能为空");
        com.chinaunicom.emergency.model.Dictionary oldDictionary = dictionaryRepository.findByPidAndIsSoftDel(dictionary.getPid(),0);
        Assert.isNull(oldDictionary,"该字典项不存在,修改失败");
        Assert.isNotEquals(dictionary.getDicCode(),oldDictionary.getDicCode(),"该字典编码无法修改,请重新填写!");
        if(!oldDictionary.getDicValue().equals(dictionary.getDicValue())){
            com.chinaunicom.emergency.model.Dictionary existDictionary = dictionaryRepository.findByParentIdAndDicValueAndIsSoftDel(dictionary.getParentId(),dictionary.getDicValue(),0);
            Assert.isNotNull(existDictionary,"同一节点下字典值重复,请勿重复创建");
        }

        dictionary.setUpdateBy(getCurrUserId());
        dictionary.setUpdateTime(new Date());
        UpdateUtil.copyNullProperties(oldDictionary,dictionary);
        dictionaryRepository.save(dictionary);
        return success();
    }

    @ApiOperation("字典删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("dictionary:delete")
    @DeleteMapping(value = "/delete")
    public Object delete(@RequestParam(value = "pid") String pid) throws CheckException {
        Assert.isBlank(pid, "字典id不能为空");
        com.chinaunicom.emergency.model.Dictionary dictionary = dictionaryRepository.findByPidAndIsSoftDel(pid,0);
        Assert.isNull(dictionary,"该角色不存在,删除失败");
        //字典是否被用户关联
        List<String> userPidList = usersRepository.getPidByDicPId(0,pid);
        Assert.isNotNull(userPidList,"该字典已被用户使用,无法删除");

        dictionary.setDeleteBy(getCurrUserId());
        dictionary.setIsSoftDel(1);
        dictionary.setDeleteTime(new Date());
        dictionaryRepository.save(dictionary);
        return success();
    }

    @ApiOperation("单个字典明细查看")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("dictionary:detail")
    @GetMapping(value = "/{pid}")
    public Object findByPid(@PathVariable String pid) throws CheckException {
        Assert.isBlank(pid, "字典id不能为空");
        com.chinaunicom.emergency.model.Dictionary dictionary = dictionaryRepository.findByPidAndIsSoftDel(pid,0);
        return success(dictionary);
    }

    @ApiOperation("分页查看字典列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("dictionary:page")
    @GetMapping(value = "/page")
    public Object findPage(@RequestParam(value = "limit", required = false) Integer limit,
                           @RequestParam(value = "page", required = false) Integer page,
                           @RequestParam(value = "parentId", required = false) String parentId,
                           @RequestParam(value = "dicCode", required = false) String dicCode
    ) throws CheckException {
        Map<String, Object> para = new HashMap<>();
        para.put("limit", limit == null ? 10 : limit);
        para.put("page", page == null ? 1 : page);
        para.put("isSoftDel", 0);
        para.put("parentId",parentId);
        para.put("dicCode",dicCode);
        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
        Page<com.chinaunicom.emergency.model.Dictionary> pages = dictionaryRepository.findAll(dictionaryService.findPageByCondition(para), getPageable(para, sort));

        return page(pages);
    }

    @ApiOperation("获取字典列表，可通过parentId查询，返回一层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = true, paramType = "header", dataType = "String")
    })
    @Permission("dictionary:listByParentId")
    @GetMapping(value = "/listByParentId")
    public Object getListByParentId(@RequestParam(value = "rootId", required = false) String rootId) throws CheckException {

        if (StringUtils.isBlank(rootId)) {
            rootId = null;
        }
        List<com.chinaunicom.emergency.model.Dictionary> orgList = dictionaryRepository.findByParentIdAndIsSoftDel(rootId,0);

        return success(orgList);
    }


    @ApiOperation("获取字典列表，可通过上级分类dicCode查询，返回一层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = true, paramType = "header", dataType = "String")
    })
    @Permission("dictionary:listByParentDicValue")
    @GetMapping(value = "/listByParentDicValue")
    public Object getListByParentDicCode(@RequestParam(value = "dicValue", required = false) String dicValue) throws CheckException {

        List<com.chinaunicom.emergency.model.Dictionary> orgList = dictionaryRepository.findListByParentDicCode(dicValue,0);

        return success(orgList);
    }
    
    
    @ApiOperation("获取字典树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = true, paramType = "header", dataType = "String")
    })
    @Permission("dictionary:tree")
    @GetMapping(value = "/tree")
    public Object getDicsTree() throws CheckException {
        List<com.chinaunicom.emergency.model.Dictionary> dicList = dictionaryRepository.findAllByParentIdIsNull();
        List resDicList = new ArrayList();
        for(com.chinaunicom.emergency.model.Dictionary dic : dicList){
            Map pMap = new HashMap();
            List<com.chinaunicom.emergency.model.Dictionary> childs = dictionaryRepository.findByParentIdAndIsSoftDel(dic.getPid(), 0);
            List childsList = new ArrayList();
            for(Dictionary dic1 : childs){
                Map map = new HashMap();
                map.put("key",dic1.getDicCode());
                map.put("value",dic1.getDicValue());
                childsList.add(map);
            }
            pMap.put("code",dic.getDicCode());
            pMap.put("value",dic.getDicValue());
            pMap.put("childs",childsList);
            resDicList.add(pMap);
        }
        return success(resDicList);
    }

}
